package com.wxg.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * 是否去研究下Apache的资源池
 * `MyFileReader`调用很频繁,如果能够利用资源池的"借出和返还"应该能够提升效率和节省资源！~
 * 
 * @author Wxg
 *
 */
public class MyFileReader {
	private String filepath;
	
	public MyFileReader(String filepath){
		// 这里已经使用了`My.rootpath`
		this.filepath = My.rootpath(filepath);
	}
	
	/**
	 * 以行为单位,将指定文件读取出来,放入一个list中！
	 * @return
	 */
	public List<String> list(){
		List<String> list = new ArrayList<String>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filepath)), "UTF8"));
			String line = null;
			while( (line=br.readLine()) != null ){
				list.add(line);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null != br){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return list;
	}
	
	/**
	 * 将指定文件的内容全部读出,放入一个String对象中返回！
	 * @return
	 */
	public String readAll(){
		StringBuilder sbb = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filepath)), "UTF8"));
			String line = null;
			while( (line=br.readLine()) != null ){
				sbb.append(line);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null != br){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sbb.toString();
	}

	public static void main(String[] args) {
		String filepath = My.rootpath("com/wxg/html/a101/head.html");
		MyFileReader mfr = new MyFileReader(filepath);
//		String str = mfr.readAll();
//		System.out.println(str);
		List<String> list = mfr.list();
		for(String str : list){
			System.out.println( str );
		}
	}
	
}
